const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
var UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const UselessFile = require('useless-files-webpack-plugin');
const ModuleIds = require('./moduleIds')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = '' // page title
const externals = {
  'vue': 'Vue',
  'element-ui': 'ElementUI',
  'element-ui': 'ELEMENT'
};
module.exports = {
  publicPath: './', // 根域上下文目录
  outputDir: 'dist', // 构建输出目录
  assetsDir: 'assets', // 静态资源目录 (js, css, img, fonts)
  lintOnSave: false, // 是否开启eslint保存检测，有效值:ture | false | 'error'
  runtimeCompiler: true, // 运行时版本是否需要编译
  transpileDependencies: [], // 默认babel-loader忽略mode_modules，这里可增加例外的依赖包名
  productionSourceMap: false, // 是否在构建生产包时生成 sourceMap 文件，false将提高构建速度
  configureWebpack: config => {

    return {
      name,
      entry: './src/main.js',
      // output: {
      //   chunkFilename: 'CS.[name].js'
      // },
      externals: {},
      module: {
        rules: [
          // {
          //     test: path.resolve('src','lib/d3.v4.js'),
          //     use: 'null-loader'
          // }
        ]
      },
      resolve: {
        alias: {
          '@': resolve('src')
        }
      },
      plugins: [
        // new ModuleIds(),
        // new webpack.ProvidePlugin({
        //   $: 'jquery',
        //   jQuery: 'jquery',
        //   'windows.jQuery': 'jquery'
        // }),
        // new UglifyJsPlugin({
        //   uglifyOptions: {
        //     compress: false
        //   }
        // }),
        // new BundleAnalyzerPlugin()//文件大小结构展示
      ],
      devtool: 'source-map',
      optimization: {
        splitChunks: {
          chunks: 'all',
          maxAsyncRequests: 20,
          maxInitialRequests: 10,
          minSize: 0,
          minChunks: 1,
          cacheGroups: {
            Vue: {
              name: 'vue',
              test: /[\\/]node_modules[\\/]vue[\\/]/,
              priority: -10
            },
            Vuex: {
              name: 'vue',
              test: /[\\/]node_modules[\\/]vuex[\\/]/,
              priority: -10
            },
            libs: {
              // name: 'chunk-libs',
              name(module) {
                const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
                // npm package names are URL-safe, but some servers don't like @ symbols
                return `npm.${packageName.replace('@', '')}`
              },
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              reuseExistingChunk: true,
              chunks: 'initial'
            },
            elementUI: {
              name: 'chunk-elementUI', // 拆分elementUI为单个包
              priority: 20, // 权重需要大于libs和app，否则将打包成libs或app
              test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // 兼容cnpm
            },
            'common': {
              name: 'common',
              test: /[\\/]src[\\/]common/,
              priority: -11
            },
            'util': {
              name: 'util',
              test: /[\\/]src[\\/]util/,
              priority: -11
            },
            'lib': {
              name: 'lib',
              test: /[\\/]src[\\/]lib/,
              priority: -11
            },
            'store': {
              name: 'store',
              test: /[\\/]src[\\/]store/,
              priority: -10
            },
          }
        }
      }
    }
  },
  chainWebpack: (config) => {
    config.set('externals', externals);
    if (process.env.NODE_ENV !== 'dev') {
      config.plugin('uglifyJs').use(UglifyJsPlugin, [{
        uglifyOptions: {
          compress: false
        }
      }]);
    }
    const svgRule = config.module.rule('svg');
    // 清除已有的所有 loader。
    // 如果你不这样做，接下来的 loader 会附加在该规则现有的 loader 之后。
    svgRule.uses.clear();


    // 需要定义根目录变量方便打包后内部引用路径出错
    config.resolve.alias.set('@', path.resolve('src'));
    // set svg-sprite-loader

    // 添加新的rule处理./src/icon文件夹的svg文件
    const dir = path.resolve(__dirname, 'src/assets/svg')
    config.module
      .rule('svg-sprite')
      .test(/\.svg$/)
      .include.add(dir).end()
      .use('svg-sprite-loader').loader('svg-sprite-loader').options({ extract: false, symbolId: 'icon-[name]' }).end()
      /* 去除所有SVG自带颜色的的两行代码*/
      // .use('svgo-loader').loader('svgo-loader')
      // .tap(options => ({ ...options, plugin: [{ removeAttrs: { attrs: 'fill' }}]})).end()


    config.plugin('svg-sprite').use(require('svg-sprite-loader/plugin', [{ plainSprite: true }]))
    config.module.rule('svg').exclude.add(dir)



    // 必须配置图片转为base64，否则图片路径无法引入
    config.module
      .rule('images')
      .test(/\.(png|jpg|gif)$/)
      .use('url-loader')
      .loader('url-loader')
      .tap(options => Object.assign(options, { limit: 1 * 1024 * 1024 }));

    // config.module
    //   .rule('images')
    //   .test(/\.(svg)(\?.*)?$/)
    //   .use('image-webpack-loader')
    //   .loader('image-webpack-loader')
    //   .options({
    //     bypassOnDebug: true
    //   })
    //   .end()


    config.module.rule('compile')
      .test(/.js$/)
      .include
      .add(path.resolve('node_modules/asn1'))
      .add(path.resolve('node_modules/asn1.js'))
      .add(path.resolve('node_modules/_asn1'))
      .add(path.resolve('node_modules/_asn1.js'))
      .end()
      .use('babel')
      .loader('babel-loader')


    config.plugin('uselessFile')
      .use(
        new UselessFile({
          root: path.resolve(__dirname, './src'), // 项目目录
          out: './fileList.json', // 输出文件列表
          clean: false, // 是否删除文件,
          exclude: [/node_modules/] // 排除文件列表
        })
      );


  },
  parallel: require('os').cpus().length > 1, // 构建时开启多进程处理babel编译
  pluginOptions: {
    // 第三方插件配置
  },
  devServer: {
    open: false,
    host: '0.0.0.0',
    // port: 8081,
    https: false,
    hotOnly: false,
    proxy: {
      // 配置跨域
      [process.env.VUE_APP_BASE_API]: {
        target: 'http://192.168.22.105:8082',
        // target: 'https://192.168.17.151',
        ws: true,
        changOrigin: true,
        logLevel: 'debug',
        secure: false,
        pathRewrite: { // 重写路径
          ['^' + process.env.VUE_APP_BASE_API]: '/vmpro'
        }
      }
    }
  }
};
